﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;

namespace CSF.BusinessCore.Service
{
    public class ErrorHandler : IErrorHandler
    {
        #region IErrorHandler 成员

        public bool HandleError(Exception error)
        {
            return true;
        }

        public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
        {

            var exceptionType = error.GetType();
            var wrapperType = typeof(ExceptionWrapper<>);
            var genericWrapperType = wrapperType.MakeGenericType(exceptionType);
            var faultExceptionType = typeof(FaultException<>);
            var genericFaultExceptionType = faultExceptionType.MakeGenericType(genericWrapperType);
            var wrapper = Activator.CreateInstance(genericWrapperType);
            var faultException = Activator.CreateInstance(genericFaultExceptionType, wrapper, new FaultReason(error.Message));
            MessageFault messageFault = ((FaultException)faultException).CreateMessageFault();
            fault = Message.CreateMessage(version, messageFault, ((FaultException)faultException).Action);

        }

        #endregion
    }
}
